package ru.maksb.exchange.service;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.maksb.exchange.domain.ClientInfo;
import ru.maksb.exchange.domain.request.LoginRequest;
import ru.maksb.exchange.exceptions.MessageParseException;

public class Authenticator {
    private final static Logger logger = LoggerFactory.getLogger(Authenticator.class);
    
    public static ClientInfo authenticate(ObjectInputStream in, ObjectOutputStream out) throws IOException, ClassNotFoundException {
        /*
         * Приходят сообщения типа "sequenceId=0;login=John"
         */
        String message = (String) in.readObject();
        logger.debug("Client attempts login: {}", message);
        try {
            LoginRequest loginRequest;
            loginRequest = MessageParser.parseLoginRequest(message);
            sendMessage(out, ResponseFactory.loginResultOk());
            logger.debug("login accepted");
            logger.info("client name - {}", loginRequest.getName());
            return new ClientInfo(loginRequest.getName());
        } catch (MessageParseException e) {
            logger.debug("login rejected");
            sendMessage(out, ResponseFactory.invalidMessage("0"));
            return null;
        }
    }
    
    private static void sendMessage(ObjectOutputStream out, String message) throws IOException {
        out.writeObject(message);
        out.flush();
        logger.debug("> {}", message);
    }
}
